package cn.fansunion.photo;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping("/photo")
public class ImageUploader extends BaseController {

	@Resource
	private PhotoDao photoDao;

	@RequestMapping(value = "upload", method = RequestMethod.POST)
	public void upload(HttpServletRequest request, Model model,
			HttpServletResponse response, Long bizid, Integer type) {
		// 定义上传路径
		String imagePath = request.getSession().getServletContext()
				.getRealPath("/image");

		JSONObject jsonObject = new JSONObject();
		response.setContentType("text/html;charset=UTF-8");

		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());

		// 判断 request 是否有文件上传,即多部分请求
		boolean multipart = multipartResolver.isMultipart(request);
		if (!multipart) {
			jsonObject.put("success", false);
			jsonObject.put("fileName", "");
			returnJsonObject(response, jsonObject);
			return;
		}
		// 转换成多部分request
		String finalFileName = handleFileList(request, imagePath);
		Long id = null;
		if (bizid != null) {
			// 临时图片存起来
			Photo photo = new Photo();
			photo.setName("name");// 这个地方需要处理，改造handleFileList方法
			photo.setUrl(finalFileName);
			photo.setBizid(bizid);
			//2表示是“临时上传的”
			photo.setStatus(2);
			photo.setType(type);
			photoDao.add(photo);
			id = photo.getId();
		}
		jsonObject.put("code", 1);
		jsonObject.put("path", finalFileName);
		jsonObject.put("name", "name");
		if (id != null) {
			jsonObject.put("id", id);
		}
		super.returnJsonObject(response, jsonObject);
	}

	// 从请求中获得图片，存储，并返回图片名称，多个图片用“,”隔开
	private static String handleFileList(HttpServletRequest request,
			String imagePath) {
		String finalFileName = "";
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		// 取得request中的所有文件名
		Iterator<String> iter = multiRequest.getFileNames();
		while (iter.hasNext()) {
			// 取得上传文件
			MultipartFile file = multiRequest.getFile(iter.next());
			if (file != null) {
				// 取得当前上传文件的文件名称
				String fileName = file.getOriginalFilename();
				// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
				if (StringUtils.isNotEmpty(fileName)) {
					String[] strs = fileName.split("\\.");
					String fileExtention = "png";
					// 重命名上传后的文件名
					if (strs.length >= 2) {
						fileExtention = strs[strs.length - 1];
					}
					try {
						String randomName = uniqueNo();
						fileName = randomName + "." + fileExtention;
						finalFileName += fileName + ",";

						String path = imagePath + File.separator + fileName;
						File localFile = new File(path);
						file.transferTo(localFile);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		// 去掉最后的“,”
		if (finalFileName.endsWith(",")) {
			finalFileName = finalFileName.substring(0,
					finalFileName.length() - 1);
		}
		return finalFileName;
	}

	/**
	 * 20位的唯一数，前17位是系统当前时间，后3位是随机数。
	 */
	public static String uniqueNo() {
		String dateStr = format(new Date(), "yyyyMMddHHmmssSSS");
		Integer threeRandomStr = RandomUtils.nextInt(100, 1000);
		return dateStr + threeRandomStr;
	}

	public static String format(Date date, String pattern) {
		return format(date, pattern, Locale.getDefault());
	}

	/**
	 * format 日期类型 格式化成字符串类型
	 */
	public static String format(Date date, String pattern, Locale locale) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern,
				locale);
		String format = simpleDateFormat.format(date);
		return format;
	}
}
